<template>
  <div class="login-page">
    <el-card>
      <template #header>面经后台管理系统</template>
    <el-form ref="form" :model="user" label-width="80px" :rules="rules">
      <el-form-item label="账号" prop="username">
        <el-input v-model="user.username"></el-input>
      </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input show-password v-model="user.password"></el-input>
        </el-form-item>
        <el-form-item>
      <el-button type="primary" @click="login">登录</el-button>
      <el-button @click="reset">重置</el-button>
    </el-form-item>
    </el-form>
    </el-card>
  </div>
</template>

<script>
import { loginAPI } from '@/api/user'

export default {
  name: 'LoginIndex',
  data () {
    return {
      user: {
        username: 'admin',
        password: 'admin'
      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          console.log('表单验证通过')
          try {
            const res = await loginAPI(this.user)
            console.log('登录结果', res)
            // localStorage.setItem('mj-pc-token', res.data.token)
            this.$store.commit('user/updateToken', res.data.token)
            this.$message.success('登录成功')
            this.$router.push('/dashboard')
          } catch (error) {
            if (error.response) {
              this.$message.error(error.response.data.message)
            } else {
              this.$message.error('登录错误')
            }
          }
        }
      })
    },
    reset () {
      this.$refs.form.resetFields()
      this.$message.success('重置成功')
    }
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  height:100vh;
  background: url(@/assets/login-bg.svg) no-repeat center / cover;
}
.el-card {
  width: 420px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  ::v-deep .el-card__header {
    text-align: center;
    background-color: #727cf5;
    color: #fff;
    height: 80px;
    line-height: 40px;
  }
}
.el-form {
  padding-right: 40px;
  .el-button:nth-child(2) {
    margin-left: 60px;
  }
}
</style>
